package com.winit.menu.repository;

import com.datastax.driver.core.querybuilder.QueryBuilder;
import com.datastax.driver.core.querybuilder.Update;
import com.winit.feature.manager.PathContainer;
import com.winit.menu.model.MatrixMenu;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.cassandra.core.CassandraOperations;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

/**
 * Created by wangjian on 2017/11/22.
 */
@Component
public class MatrixMenuOperations {
    private static Logger logger = LoggerFactory.getLogger(MatrixMenuOperations.class);
    private static final String TABLE = "matrix_menu";
    @Autowired
    private CassandraOperations cassandraOperations;
    @Autowired
    private PathContainer pathContainer;

    public void updateMenu(MatrixMenu menu) {
        cassandraOperations.update(menu);
        pathContainer.updatePath(menu.getId(), menu.getParent_id(), menu.getMenu_name(), menu.getChildren());
    }

    //    @Transactional
    public void updateByIdForPropertiesNotNull(MatrixMenu menu) {
        Update update = QueryBuilder.update(TABLE);
        if (null != menu.getParent_id()) {
            update.with(QueryBuilder.set("parent_id", menu.getParent_id()));
        }
        if (null != menu.getStatus()) {
            update.with(QueryBuilder.set("status", menu.getStatus()));
        }
        if (null != menu.getChildren()) {
            update.with(QueryBuilder.set("children", menu.getChildren()));
        }
        if (null != menu.getSys()) {
            update.with(QueryBuilder.set("sys", menu.getSys()));
        }
        if (null != menu.getMenu_data()) {
            update.with(QueryBuilder.set("menu_data", menu.getMenu_data()));
            update.with(QueryBuilder.set("menu_name", menu.getMenu_data().get("name")));
        }
        if (null != menu.getLevel()) {
            update.with(QueryBuilder.set("level", menu.getLevel()));
        }
        if (null != menu.getReq_id()) {
            update.with(QueryBuilder.set("req_id", menu.getReq_id()));
        }
        if (null != menu.getIs_del()) {
            update.with(QueryBuilder.set("is_del", menu.getIs_del()));
        }
        update.where(QueryBuilder.eq("id", menu.getId()));
        cassandraOperations.execute(update);
        pathContainer.updatePath(menu.getId(), menu.getParent_id(), menu.getMenu_name(), menu.getChildren());
    }

    public void deleteMenu(MatrixMenu menu) {
        cassandraOperations.delete(menu);
    }
}
